package demo3;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-09
 * Time: 10:59
 */
public class TestDemo3 {

    /**
     * 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("请输入你要扫描的指定目录");
        Scanner scan1 = new Scanner(System.in);
        String root = scan1.next();
        File file = new File(root);
        if(!file.isDirectory()){
            System.out.println("不是目录名~~~");
            return;
        }
        System.out.println("请输入你要查找的内容");
        Scanner scan2 = new Scanner(System.in);
        String toFind = scan2.next();

        scanDir(file,toFind);
    }
    public static void scanDir(File file ,String toFind){
        File[] files = file.listFiles();
        if(files==null||files.length==0){
           // System.out.println("该目录里面没有文件~~~");
            return;
        }
        for(File f : files){
            if(f.isDirectory()){
                scanDir(f,toFind);
            }else {
                tryFInd(f,toFind);
            }
        }
    }
    public static void tryFInd(File f, String toFind){
        if(f.getName().contains(toFind)){
            try {
                System.out.println("找到与文件名相匹配的文件" + f.getCanonicalPath());
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try(InputStream inputStream = new FileInputStream(f)){
            byte[] bytes =new byte[1024];
            StringBuilder res = new StringBuilder();
                Scanner scan = new Scanner(inputStream);
                while(scan.hasNext()){
                    res.append(scan.next());
                }
                if(res.indexOf(toFind)>=0){
                    System.out.println("找到了与文件内容相同的文件路径 " + f.getCanonicalPath());
                    return;
                }

        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
